package com.shimao.celnet.payment.controller.api;

import com.shimao.celnet.payment.config.ConstantConfig;
import com.shimao.celnet.payment.model.PPay;
import com.shimao.celnet.payment.model.PPayCust;
import com.shimao.celnet.payment.model.PPayDetail;
import com.shimao.celnet.payment.model.request.CallIn_OutPayReqInRequest;
import com.shimao.celnet.payment.model.request.Payment;
import com.shimao.celnet.payment.model.response.ErrorInfoEnum;
import com.shimao.celnet.payment.model.response.ResponseJson;
import com.shimao.celnet.payment.service.*;
import com.shimao.celnet.payment.service.impl.apiservice.CallOut_TLPublicService;
import com.shimao.celnet.payment.util.FinalUtil;
import com.shimao.celnet.payment.util.MyDateUtil;
import io.swagger.annotations.Api;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 微信、支付宝支付请求接口
 * 外部系统 → 支付系统，数据：微信、支付宝支付请求数据
 * Created by Galen on 2018/11/27.
 */
@RestController
@RequestMapping(value = "/payment")
@Api("接口：pay-211-外部微信、支付宝支付请求<OutAlipayOrWechatPayReqIn> 外部系统 → 支付系统，数据：微信、支付宝支付请求数据")
public class CallIn_OutAlipayOrWechatPayReqInController {

    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private PPayCustService pPayCustService;

    @Autowired
    private CallOut_TLPublicService callOut_tlPublicService;

    @Autowired
    private SCodeNameService sCodeNameService;

    @Autowired//支付申请
    private PPayService pPayService;

    @Autowired//房间
    private BHouseService bHouseService;

    @Autowired//小区
    private BEstateService bEstateService;

    @Autowired //商家
    private PPayBusinessService pPayBusinessService;

    @Autowired
    private ConstantConfig constantConfig;

    @RequestMapping(value = "/alipayOrWechatPay" , method = RequestMethod.POST)
    public String alipayOrWechatPayReq(@RequestBody @Valid CallIn_OutPayReqInRequest requestJson, BindingResult result){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        ResponseJson retJson = new ResponseJson(ErrorInfoEnum.SUCCESS, "");
        logger.info("pay-211-外部微信、支付宝支付请求<OutAlipayOrWechatPayReqIn>请求JSON:" + requestJson.toString());
        //通过valid验证
        if (result.hasErrors()) {
            for (FieldError error : result.getFieldErrors()) {
                logger.debug("缺少必要参数：" + error.getDefaultMessage());
                retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS, error.getDefaultMessage());
                return retJson.toString();
            }
        }
        PPay pPay = new PPay();
        String payGuid = pPayService.getGuid();
        pPay.setGuid(payGuid);
        pPay.setCreatedUserGuid(FinalUtil.INTER_FACE_USER_ID);
        pPay.setUpdateUserGuid(FinalUtil.INTER_FACE_USER_ID);
        pPay.setBusinessType(requestJson.getpOrderType());    //	业务类型
        pPay.setPayType(requestJson.getpType());             //支付方式： A03快捷支付
        pPay.setPayAmount(requestJson.getpMoney());    //	支付金额
        pPay.setPayStartTime(String.valueOf(System.currentTimeMillis()));//	支付开始时间
        if(requestJson.getEstateId() != null && requestJson.getEstateId()!= ""){
            if(bEstateService.getBySfGuid(requestJson.getEstateId()) != null){
                pPay.setEstateGuid(bEstateService.getBySfGuid(requestJson.getEstateId()).getGuid());    //	小区guid
                pPay.setEstateSfGuid(requestJson.getEstateId());    //	小区SF-GUID
            }else {
                pPay.setEstateGuid(pPayBusinessService.getByGuid(requestJson.getEstateId()).getGuid());
                pPay.setEstateSfGuid(requestJson.getEstateId());    //	小区SF-GUID
            }
        }
        if(requestJson.getHouseId() != null && requestJson.getHouseId()!= ""){
            if(requestJson.getEstateId() == "" || requestJson.getEstateId() == null){
                pPay.setEstateGuid(bHouseService.getBySfGuid(requestJson.getHouseId()).getEstateGuid());
            }
            pPay.setHourceGuid(bHouseService.getBySfGuid(requestJson.getHouseId()).getGuid());    //	支付房间guid
        }
        pPay.setHourceSfGuid(requestJson.getHouseId());    //	支付房间SF-GUID
        pPay.setPayUserSfGuid(requestJson.getMeruserid());    //	支付用户SF-GUID
        pPay.setPayUserName(requestJson.getUserName());    //	支付用户名称
        pPay.setPayRemark(requestJson.getpRemark());       //	支付说明
        pPay.setGoBackUrl(requestJson.getGoBackUrl());     //   支付成功回调url
        pPay.setPayAppType(requestJson.getpAppType());     //   app类型
        pPay.setPayAppName(requestJson.getpAppName());     //   APP名字
        pPay.setPayAppPackage(requestJson.getpAppPackage());//  APP包
        pPay.setPayCusip(requestJson.getpCusip());         //   终端ip
        pPay.setAppKey(request.getHeader(FinalUtil.HEADER_APP_KEY));//app_key
        pPay.setInterfaceId(request.getHeader(FinalUtil.HEADER_INTERFACE_ID));//接口id
        List<Payment> paymentList = requestJson.getPaymentList();
        List<PPayDetail> pPayDetailList = new ArrayList<PPayDetail>();
        for (Payment payment : paymentList) {
            PPayDetail pPayDetail = new PPayDetail();
            pPayDetail.setExsysDetailId(payment.getReceivableId());//外部系统明细id
            pPayDetail.setAmount(payment.getTotalReceivableAmount());//明细金额
            pPayDetail.setRemark(payment.getbRemark());//明细说明
            //支付申请记录明细保存
            pPayDetailList.add(pPayDetail);
        }
        //根据注册信息的商户id获取商户信息
        PPayCust payCust = getTLMessage(pPay.getEstateGuid(), pPay.getPayType());
        try {
            Map <String,String> map = new TreeMap<>();
            String BusinessType =  sCodeNameService.getNameByCode(pPay.getBusinessType());
            if(BusinessType==null||BusinessType==""){
                BusinessType = pPay.getBusinessType();
            }
            if (FinalUtil.ALIPAY_PAY_TYPE.equals(pPay.getPayType())){
                //请求通联callout
                logger.info("***************************请求通联支付宝支付："+pPay.getPayAmount()+"*******>>>>>pPayCust："+payCust.getCustId());
                map = callOut_tlPublicService.pay(pPay.getPayAmount(), MyDateUtil.NotString(payGuid), pPay.getPayType(), BusinessType, pPay.getPayRemark(), "000000", constantConfig.getTlReturnURL(),payCust);
                logger.info("***************************通联支付宝响应参数："+map.toString());
            }else {
                //请求通联callout
                logger.info("***************************请求通联微信支付："+pPay.getPayAmount()+"*******>>>>>pPayCust："+payCust.getCustId());
                map = callOut_tlPublicService.payWeChat(pPay.getPayAmount(), MyDateUtil.NotString(payGuid), pPay.getPayType(), BusinessType, pPay.getPayRemark(),pPay, constantConfig.getTlReturnURL(),payCust);
                logger.info("***************************通联微信响应参数："+map.toString());
            }
            if("SUCCESS".equals(map.get(FinalUtil.RETCDE))){
                pPay.setUpdateDate(new Date());
                pPay.setTrxid(map.get("trxid"));//通联唯一流水单号
                retJson.setErrorMessage(map.get(FinalUtil.ERRMSG));
                retJson.addBody(FinalUtil.TRXSTATUS,map.get(FinalUtil.TRXSTATUS));
                retJson.addBody("trxid",map.get("trxid"));
                retJson.addBody("paymentId",payGuid);
                if(FinalUtil.ALIPAY_PAY_TYPE.equals(pPay.getPayType()) &&  map.get("payinfo") != null && "".equals(map.get("payinfo"))){  //支付宝的返回调用的app的需要，拼接后才能使用
                    retJson.addBody("payInfo",alipayScanToApp(map.get("payinfo")));
                    pPay.setPayInfoUrl(alipayScanToApp(map.get("payinfo")));//APP支付返回调起sdk的参数json字符串
                }else {
                    retJson.addBody("payInfo",map.get("payinfo"));
                    pPay.setPayInfoUrl(map.get("payinfo"));//APP支付返回调起sdk的参数json字符串
                }

            }else {
                pPay.setPayStatus(FinalUtil.PAY_STATUS_FAILUE);
                retJson = new ResponseJson(ErrorInfoEnum.PAY_RESULT_TYPE, "FAIL");
            }

        }catch (Exception e){
            e.printStackTrace();
            logger.debug("通联异常参数：" + e.getMessage());
            retJson = new ResponseJson(ErrorInfoEnum.PAY_RESULT_TYPE, e.getMessage());
        }

        return retJson.toString();
    }


    /**
     * 将支付宝的二维码支付方式转化为app支付
     *
     * @param qrurl 例如 https://qr.alipay.com/bax00493ktpkya6i13s6002f
     * @return
     */
    public static String alipayScanToApp(String qrurl) {
        qrurl = qrurl + "?_s=web-other";//1.二维码url后面拼接?_s=web-other"
        String appUrl = "";
        try {
            qrurl = URLEncoder.encode(qrurl, "Utf8");//2.将拼接后urlecode
            qrurl = "alipays://platformapi/startapp?saId=10000007&clientVersion=3.7.0.0718&qrcode=" + qrurl;//在前面拼接打开支付宝app的方式
            appUrl = "https://ds.alipay.com/?from=mobilecodec&scheme=" + URLEncoder.encode(qrurl, "Utf8");//在前面再拼接跳往支付宝的url

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return appUrl;
    }

    /**
     * 根据小区sfid查询通联账户信息
     * @param estateGuid
     * @return
     */
    public PPayCust getTLMessage(String estateGuid, String payType) {
        return pPayCustService.getBySfGuid1(estateGuid, payType);
    }
}
